/**
 * 通知管理模块配置文件
 * 该文件定义了通知管理模块的相关配置，包括模块名称、接口定义、表格列配置、搜索配置和表单配置。
 * @module noticeConfig
 */
import dayjs from 'dayjs'
import { ref } from 'vue'
// import Public from '/@/api/public' // 移除
import type { ApiResponse, ListResponse } from '/@/types/api'
// import { getActivityId, getActivityName, getSignUpType } from '/@/utils/activityHelper' // getActivityId 和 getActivityName 未使用
import { getSignUpType } from '/@/utils/activityHelper' // 只保留 getSignUpType
import request from '/@/utils/request'

// 定义 FormItem 接口
export interface FormItem {
  prop: string
  label: string
  component: string
  placeholder?: string
  componentProps?: any
  options?: any[] // 通常用于 select, radio, checkbox 等
  rules?: any[]
  labelWidth?: string | number
  required?: boolean
  [key: string]: any // 允许其他自定义属性
}

export const moduleName = '通知'
export const moduleApi = '/api/notification/task'

// 通知任务接口定义
export interface NotificationTask {
  id?: number
  title: string
  activityId: string
  notifyType: 'app' | 'sms'
  notifySendStatus: '0' | '1'
  content: string
  userId: string | string[]
  notifyTime: string
  remark?: string
  createdAt?: string
  updatedAt?: string
  attachment?: any[]
  isAllUsers?: boolean
  // useAgendaContent?: boolean // 注释掉此字段
  // 新增字段，支持部门ID
  deptId?: string
  // 新增备份字段，用于处理响应式数据丢失问题
  _userIdBackup?: string | string[]
}

// 通知详情接口定义
export interface NotificationDetail {
  id?: number
  taskId: number
  userId: string
  content: string
  notifySendStatus: '0' | '1'
  notifyReceiveStatus: '0' | '1'
  notifyTime: string
}

// 选项数据类型
interface SelectOption {
  value: string
  label: string
  disabled?: boolean
}

// 状态字典
export const statusDict = {
  notifySendStatus: {
    '0': '未发送',
    '1': '已发送',
  },
  notifyReceiveStatus: {
    '0': '未接收',
    '1': '已接收',
  },
  notifyType: {
    app: '应用内',
    // sms: '短信',
  },
}

/**
 * 用户选项数据（从API获取）
 */
export const userOptions = ref<SelectOption[]>([])

/**
 * 获取用户列表
 * @param query 搜索关键词
 */
export const getUserList = async (query?: string) => {
  try {
    console.log('开始获取用户列表数据, 搜索关键词:', query)
    const params: Record<string, any> = {
      activityId: localStorage.getItem('hongyouActId') || '',
    }

    // 如果有搜索关键词，添加到查询参数
    if (query) {
      params.name = query // 使用name参数进行搜索
    }

    const res = await request.get<any, ApiResponse<ListResponse<any>>>('/api/player/all', {
      params,
    })

    console.log('用户API返回数据:', res?.result)

    if (res?.result?.rows) {
      userOptions.value = res.result.rows.map((item: any) => ({
        value: String(item.id), // 确保value是用户ID
        label: item.name || item.username || `用户ID:${item.id}`,
      }))
      console.log('处理后的用户选项:', userOptions.value)
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
  }
}

/**
 * 通知类型选项
 */
export const notifyTypeOptions = ref<SelectOption[]>(
  Object.entries(statusDict.notifyType).map(([value, label]) => ({
    value,
    label,
  }))
)

/**
 * 发送状态选项
 */
export const sendStatusOptions = ref<SelectOption[]>(
  Object.entries(statusDict.notifySendStatus).map(([value, label]) => ({
    value,
    label,
  }))
)

/**
 * 搜索字段配置
 */
export const searchFields = ref([
  {
    prop: 'notifyType',
    label: '',
    component: 'select',
    placeholder: '通知类型',
    componentProps: {
      options: notifyTypeOptions,
      clearable: true,
      style: 'width: 120px',
    },
  },
  {
    prop: 'notifySendStatus',
    label: '',
    component: 'select',
    placeholder: '发送状态',
    componentProps: {
      options: sendStatusOptions,
      clearable: true,
      style: 'width: 120px',
    },
  },
  {
    prop: 'title',
    label: '',
    component: 'input',
    placeholder: '请输入标题',
    componentProps: {
      clearable: true,
      style: 'width: 200px',
      prefix: '标题',
    },
  },
])

/**
 * 表格列配置
 */
export const tableColumns = [
  { label: '标题', prop: 'title', minWidth: 120 },
  // {
  //   label: '通知类型',
  //   prop: 'notifyType',
  //   minWidth: 100,
  //   customRender: true,
  //   formatter: (row: any) => statusDict.notifyType[row.notifyType as keyof typeof statusDict.notifyType] || row.notifyType,
  // },
  // {
  //   label: '通知内容',
  //   prop: 'content',
  //   minWidth: 200,
  //   customRender: true,
  // },
  // {
  //   label: '附件',
  //   prop: 'attachment',
  //   minWidth: 150,
  //   customRender: true,
  // },
  { label: '备注', prop: 'remark', minWidth: 150, showOverflowTooltip: true },
  { label: '创建时间', prop: 'createdAt', minWidth: 160 },
  {
    label: '操作',
    prop: 'operations',
    width: 200,
    fixed: 'right',
    customRender: true,
  },
]

/**
 * 表单字段配置
 */
export const formFields = ref([
  {
    prop: 'title',
    label: '标题',
    component: 'input',
    rules: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  },
  {
    prop: 'notifyTime',
    label: '通知时间',
    component: 'date-picker',
    componentProps: {
      type: 'datetime',
      valueFormat: 'YYYY-MM-DD HH:mm:ss',
    },
    rules: [{ required: true, message: '请选择通知时间', trigger: 'change' }],
  },
  {
    prop: 'userId',
    label: '接收人',
    component: 'RecipientSelector',
    visible: false,
    rules: [],
  },
  {
    prop: 'remark',
    label: '备注',
    component: 'input',
    componentProps: {
      type: 'textarea',
      rows: 3,
    },
  },
])

/**
 * 详情字段配置
 */
export const detailFields = [
  {
    label: '标题',
    prop: 'title',
  },
  // {
  //   label: '通知类型',
  //   prop: 'notifyType',
  //   render: (val: string) => statusDict.notifyType[val as keyof typeof statusDict.notifyType] || val,
  // },
  {
    label: '发送状态',
    prop: 'notifySendStatus',
    render: (val: string) => statusDict.notifySendStatus[val as keyof typeof statusDict.notifySendStatus] || val,
  },
  {
    label: '通知时间',
    prop: 'notifyTime',
    render: (val: string) => (val ? dayjs(val).format('YYYY-MM-DD HH:mm:ss') : '-'),
  },
  {
    label: '接收人',
    prop: 'userId',
    render: (val: string[]) => (Array.isArray(val) ? val.join(', ') : val),
  },
  {
    label: '通知内容',
    prop: 'content',
    render: (val: string) => `<div class="content-preview">${val || '无内容'}</div>`,
  },
  {
    label: '创建时间',
    prop: 'createdAt',
    render: (val: string) => (val ? dayjs(val).format('YYYY-MM-DD HH:mm:ss') : '-'),
  },
  { label: '备注', prop: 'remark' },
]

/**
 * 详情表格配置
 */
export const detailTableColumns = [
  { label: '接收人', prop: 'user.name' },
  {
    label: '发送状态',
    prop: 'notifySendStatus',
    dictionary: statusDict.notifySendStatus,
  },
  {
    label: '接收状态',
    prop: 'notifyReceiveStatus',
    dictionary: statusDict.notifyReceiveStatus,
  },
  { label: '通知时间', prop: 'notifyTime' },
  {
    label: '操作',
    prop: 'operations',
    type: 'operation',
    operations: [
      {
        label: '重新发送',
        type: 'primary',
        action: 'resend',
        show: (row: NotificationDetail) => row.notifySendStatus === '0',
      },
      {
        label: '查看内容',
        type: 'primary',
        action: 'view',
      },
    ],
  },
]

/**
 * 格式化表单数据，将表单数据转换为API需要的格式
 * @param formData 表单数据
 * @returns 格式化后的表单数据
 */
export const formatFormData = (formData: any): any => {
  // 防止修改原对象
  const clonedData = JSON.parse(JSON.stringify(formData))

  // 获取当前报名类型
  const signUpType = localStorage.getItem('signUpType') || '1'

  // 删除可能存在但API不需要的字段
  delete clonedData.isAllUsers
  // delete clonedData.useAgendaContent // 注释掉删除逻辑
  delete clonedData._userIdBackup

  // 处理接收人数据
  if (signUpType === '1') {
    // 用户选择模式
    if (clonedData.userId === 'all') {
      // 全选情况下，传递特殊标识
      clonedData.userId = 'all'
      // 确保删除deptId
      delete clonedData.deptId
    } else if (Array.isArray(clonedData.userId) && clonedData.userId.length > 0) {
      // 有选择的用户，转换为字符串格式
      clonedData.userId = clonedData.userId.join(',')
      // 确保删除deptId
      delete clonedData.deptId
    } else {
      // 没有选择任何用户，设置为空字符串
      clonedData.userId = ''
      // 确保删除deptId
      delete clonedData.deptId
    }
  } else if (signUpType === '2') {
    // 部门选择模式
    if (clonedData.deptId) {
      // 有部门ID，确保删除userId字段
      delete clonedData.userId
    } else {
      // 没有部门ID，按照原有逻辑处理userId
      if (clonedData.userId === 'all') {
        clonedData.userId = 'all'
      } else if (Array.isArray(clonedData.userId) && clonedData.userId.length > 0) {
        clonedData.userId = clonedData.userId.join(',')
      } else {
        clonedData.userId = ''
      }
    }
  }

  // 确保时间格式正确
  if (clonedData.notifyTime) {
    clonedData.notifyTime = dayjs(clonedData.notifyTime).format('YYYY-MM-DD HH:mm:ss')
  }

  console.log('格式化后的表单数据:', clonedData)
  return clonedData
}

/**
 * 解析API返回数据
 * @param apiData API返回的数据
 * @returns 解析后的数据
 */
export const parseApiData = (apiData: any): any => {
  const data = { ...apiData }
  const signUpType = getSignUpType()

  console.log(apiData)
  console.log('解析API数据，原始userId:', data.userId, '类型:', typeof data.userId)

  if (signUpType === '1') {
    // 用户选择模式
    // 处理接收人字段
    if (typeof data.userId === 'string') {
      // 检查是否为"全部人员"
      if (data.userId === 'all') {
        data.isAllUsers = true
        data.userId = 'all'
        console.log('解析为全选模式')
      } else {
        data.isAllUsers = false
        data.userId = data.userId.split(',').filter(Boolean)
        console.log('解析为个人选择:', data.userId)
      }
    } else if (data.userId === null || data.userId === undefined) {
      // 处理空值情况
      data.isAllUsers = false
      data.userId = []
      console.log('处理空值情况')
    }
    // 确保没有部门ID
    delete data.deptId
  } else if (signUpType === '2') {
    // 部门选择模式
    // 如果有deptId，将其作为userId返回
    if (data.deptId) {
      data.userId = data.deptId
      console.log('部门模式，使用deptId:', data.deptId)
    } else if (data.userId && data.userId !== '') {
      // 如果没有deptId但有userId，可能是部门ID
      if (typeof data.userId === 'string') {
        // 保持字符串
      } else if (Array.isArray(data.userId) && data.userId.length > 0) {
        data.userId = data.userId[0]
      }
      console.log('部门模式，处理后userId:', data.userId)
    }
  }

  console.log('解析完成，结果:', data.userId)
  return data
}

export const API = {
  list: '/notice/list',
  detail: '/notice/',
  add: '/notice/add',
  update: '/notice/update',
  delete: '/notice/delete',
  publish: '/notice/publish',
  cancelPublish: '/notice/cancelPublish',
  uploadUrl: '/notice/upload',
  activityList: '/activity/list', // 活动列表 -> 用于活动选择下拉框
  getPlayerAll: '/api/player/all', // 新增：获取活动用户列表
}

export const formItems: FormItem[] = [
  // ... existing code ...
]
